﻿'/*
' * FAHWatch7 clsSettings  Copyright Marvin Westmaas ( mtm )
' *
' * This program is free software; you can redistribute it and/or
' * modify it under the terms of the GNU General Public License
' * as published by the Free Software Foundation; version 2
' * of the License. See the included file GPLv2.TXT.
' * 
' * This program is distributed in the hope that it will be useful,
' * but WITHOUT ANY WARRANTY; without even the implied warranty of
' * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
' * GNU General Public License for more details.
' * 
' * You should have received a copy of the GNU General Public License
' * along with this program; if not, write to the Free Software
' * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
' */
'/*	
Public Class clsSettings
    Private m_firstRun As Boolean = True
#Region "Fixed properties and settings"
    Public Property Settings As Dictionary(Of String, String)
        Get
            Return m_Settings
        End Get
        Set(value As Dictionary(Of String, String))
            m_Settings = value
        End Set
    End Property
    Public Property EOC_Net_Failure As DateTime
        Get
            Return DateTime.Parse(m_Settings("eoc_net_failure"))
        End Get
        Set(value As DateTime)
            m_Settings("eoc_net_failure") = value.ToString("s")
        End Set
    End Property
    Public Property LiveView As Boolean
        Get
            Return CBool(m_Settings("liveview"))
        End Get
        Set(ByVal value As Boolean)
            m_Settings("liveview") = value.ToString
        End Set
    End Property
    Public Property DefaultSummary As String
        Get
            Return m_Settings("defaultsummary")
        End Get
        Set(ByVal value As String)
            m_Settings("defaultsummary") = value
        End Set
    End Property
    Public Property StartWithWindows As Boolean
        Get
            Return CBool(m_Settings("startwithwindows"))
        End Get
        Set(ByVal value As Boolean)
            m_Settings("startwithwindows") = value.ToString
        End Set
    End Property
    Public Property MinimizeToTray As Boolean
        Get
            Return CBool(m_Settings("minimizetotray"))
        End Get
        Set(ByVal value As Boolean)
            m_Settings("minimizetotray") = value.ToString
        End Set
    End Property
    Public Property NetworkPort As String
        Get
            Try
                Return m_Settings("network_port")
            Catch ex As Exception
                Return "49153"
            End Try
        End Get
        Set(value As String)
            m_Settings("network_port") = value
        End Set
    End Property
    Public Property ShowEOCIcon As Boolean
        Get
            Return CBool(m_Settings("eocicon"))
        End Get
        Set(value As Boolean)
            m_Settings("eocicon") = CStr(value)
        End Set
    End Property
    Public ReadOnly Property FirstRun As Boolean
        Get
            Return m_firstRun
        End Get
    End Property
    Public Property DefaultView As String
        Get
            Return m_Settings("defaultview")
        End Get
        Set(value As String)
            m_Settings("defaultview") = value
        End Set
    End Property
    Public Property LocalClientName As String
        Get
            Return m_Settings("localname")
        End Get
        Set(value As String)
            m_Settings("localname") = value
        End Set
    End Property
    Public Property StartFC As Boolean
        Get
            Return CBool(m_Settings("startfc"))
        End Get
        Set(value As Boolean)
            m_Settings("startfc") = value.ToString
        End Set
    End Property
    Public Property StartMinimized As Boolean
        Get
            Return CBool(m_Settings("startminimized"))
        End Get
        Set(value As Boolean)
            m_Settings("startminimized") = value.ToString
        End Set
    End Property
    Public Property AutoDownloadSummary As Boolean
        Get
            Return CBool(m_Settings("autodownloadsummary"))
        End Get
        Set(value As Boolean)
            m_Settings("autodownloadsummary".ToLower) = value.ToString
        End Set
    End Property
    Public Property EOCNotify As Boolean
        Get
            Return CBool(m_Settings("eocnotify"))
        End Get
        Set(value As Boolean)
            m_Settings("eocnotify") = value.ToString
        End Set
    End Property
    Public Property NotifyOption As clsNotifyOptions.eNotifyOption
        Get
            Try
                Return CType([Enum].Parse(GetType(clsNotifyOptions.eNotifyOption), m_Settings("notify_by")), clsNotifyOptions.eNotifyOption)
            Catch ex As Exception
                Return clsNotifyOptions.eNotifyOption.TrayIcon
            End Try
        End Get
        Set(value As clsNotifyOptions.eNotifyOption)
            If HasSetting("notifyfail_by") Then
                ChangeSetting("notifyfail_by", value.ToString)
            Else
                AddSetting("notifyfail_by", value.ToString)
            End If
        End Set
    End Property
    Public Property Notify_EUE As Boolean
        Get
            Return CBool(m_Settings("notifyeue"))
        End Get
        Set(value As Boolean)
            m_Settings("notifyeue") = value.ToString
        End Set
    End Property
    Public Property Notify_EUE_ByRate As Boolean
        Get
            Return CBool(m_Settings("notifyeue_rate"))
        End Get
        Set(value As Boolean)
            m_Settings("notifyeue_rate") = value.ToString
        End Set
    End Property
    Public Property Notify_EUE_Always As Boolean
        Get
            Return CBool(m_Settings("notifyeue_always"))
        End Get
        Set(value As Boolean)
            m_Settings("notifyeue_always") = value.ToString
        End Set
    End Property
    Public Property Notify_Failure As Boolean
        Get
            Return CBool(m_Settings("notifyfail"))
        End Get
        Set(value As Boolean)
            m_Settings("notifyfail") = value.ToString
        End Set
    End Property
    Public Property NotifyRate As Double
        Get
            Return CDbl(m_Settings("notifyrate"))
        End Get
        Set(value As Double)
            m_Settings("notifyrate") = CStr(value)
        End Set
    End Property
    Public Property Notify_UseRules As Boolean
        Get
            Return CBool(m_Settings("usefilterrules"))
        End Get
        Set(value As Boolean)
            m_Settings("usefilterrules") = value.ToString
        End Set
    End Property
    Public Property DisableEOC As Boolean
        Get
            Return CBool(m_Settings("eocdisable"))
        End Get
        Set(value As Boolean)
            m_Settings("eocdisable") = value.ToString
        End Set
    End Property
    Public Property EocCustomSignature As String
        Get
            Return m_Settings("eoccustomsignature")
        End Get
        Set(value As String)
            m_Settings("eoccustomsignature") = value
        End Set
    End Property
    Public Property ParseLogsOnInterval As Boolean
        Get
            Return CBool(m_Settings("parseoninterval"))
        End Get
        Set(value As Boolean)
            m_Settings("parseoninterval") = value.ToString
        End Set
    End Property
    Public Property ParseOnEOCUpdate As Boolean
        Get
            Return CBool(m_Settings("parselogseoc"))
        End Get
        Set(value As Boolean)
            m_Settings("parselogseoc") = value.ToString
        End Set
    End Property
    Public Property ParserInterval As TimeSpan
        Get
            Return TimeSpan.Parse(m_Settings("parserinterval"))
        End Get
        Set(value As TimeSpan)
            m_Settings("parserinterval") = value.ToString
        End Set
    End Property
    Public Property ViewDetails As Boolean
        Get
            Return CBool(m_Settings("history_viewdetails"))
        End Get
        Set(value As Boolean)
            m_Settings("history_viewdetails") = value.ToString
        End Set
    End Property
    Public Property tcMain_splitterdistance As Int32
        Get
            Return CInt(m_Settings("history_tcmain_splitterdistance"))
        End Get
        Set(value As Int32)
            m_Settings("history_tcmain_splitterdistance") = CStr(value)
        End Set
    End Property
    Public Property history_tcdetails_splitterdistance As Int32
        Get
            Return (CInt(m_Settings("history_tcdetails_splitterdistance")))
        End Get
        Set(value As Int32)
            m_Settings("history_tcdetails_splitterdistance") = CStr(value)
        End Set
    End Property
#Region "Settings functions"
    Public Function GetSettings() As Boolean
        Try
            Dim _b As Dictionary(Of String, String) = m_Settings
            m_Settings = sqdata.ReadSettings
            For Each _default In _b
                If Not m_Settings.ContainsKey(_default.Key) Then m_Settings.Add(_default.Key, _default.Value)
            Next
            Return m_Settings.Count > 0
        Catch ex As Exception
            WriteError(ex.Message, Err)
            Return False
        End Try
    End Function
    Public Function SaveSettings() As Boolean
        Try
            Return sqdata.StoreSettings(m_Settings)
        Catch ex As Exception
            WriteError(ex.Message, Err)
            Return False
        End Try
    End Function
    Public ReadOnly Property HasSetting(Name As String) As Boolean
        Get
            Return m_Settings.ContainsKey(Name)
        End Get
    End Property
    Public ReadOnly Property Setting(Name As String) As Object
        Get
            If m_Settings.ContainsKey(Name) Then
                Return m_Settings(Name)
            Else
                Return ""
            End If
        End Get
    End Property
    Public Sub ChangeSetting(Name As String, Value As String)
        If m_Settings.ContainsKey(Name) Then
            m_Settings(Name) = Value
        Else
            AddSetting(Name, Value)
        End If
    End Sub
    Public Sub AddSetting(p1 As String, p2 As String)
        If Not m_Settings.ContainsKey(p1) Then
            m_Settings.Add(p1, p2)
        Else
            ChangeSetting(p1, p2)
        End If
    End Sub
#End Region
#End Region

#Region "Form actions/properties"

#Region "Options form actions"
    Private _frmOptions As frmOptions
    Private m_Settings As New Dictionary(Of String, String)
    Public ReadOnly Property IsOptionsFormActive As Boolean
        Get
            Return _frmOptions.Visible
        End Get
    End Property
    Public Sub ShowOptionsForm(Optional ByVal Owner As Form = Nothing)
        Try
            If IsNothing(_frmOptions) Or (Not IsNothing(_frmOptions) AndAlso _frmOptions.IsDisposed) Then _frmOptions = New frmOptions
            _frmOptions.ShowOptions(Owner)
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
    Public Sub CloseOptionsForm()
        _frmOptions.CloseForm()
    End Sub
#End Region

#Region "Notification form actions/properties"
    Private _frmNotify As frmNotifyOptions
    Private _notifyOptions As New clsNotifyOptions
    Public Class clsNotifyOptions
        Public NotifyEUE As Boolean = False
        Public EUE_by_Rate As Boolean = False
        Public EUE_always As Boolean = True
        Public NotifyRATE As Double = 80.0
        Public notifyFAILURE As Boolean = True
        Public NotifyOption As eNotifyOption = eNotifyOption.TrayIcon
        Public NotifyRules As Boolean = False
        Public Enum eNotifyOption
            TrayIcon
            PopUpForm
        End Enum
    End Class
    Public Property notify As clsNotifyOptions
        Get
            Return _notifyOptions
        End Get
        Set(value As clsNotifyOptions)
            _notifyOptions = value
        End Set
    End Property
    Public ReadOnly Property IsNotifyFormActive As Boolean
        Get
            Return _frmNotify.Visible
        End Get
    End Property
    Public Sub ShowNotifyForm(Optional Owner As Form = Nothing)
        Try
            If IsNothing(_frmNotify) Or (Not IsNothing(_frmNotify) AndAlso _frmNotify.IsDisposed) Then _frmNotify = New frmNotifyOptions
            _frmNotify.Init(Owner)
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
#Region "Notify filters"
    Public Class clsNFilter
        Public ucFilter As ucNotifyFilter
        Public fName As String = String.Empty  ' filter name
        Public ReadOnly Property ClientName As String
            Get
                Dim cName As String = ""
                If InStr(fName, "_") = 0 Then
                    cName = fName
                Else
                    cName = fName.Substring(8, fName.IndexOf("_", 8) - 8)
                End If
                Return cName
            End Get
        End Property
        Public ReadOnly Property SlotID As String 'return -1 for client rule
            Get
                Dim cName As String = ""
                If InStr(fName, "_") = 0 Then
                    cName = fName
                Else
                    cName = fName.Substring(8, fName.IndexOf("_", 8) - 8)
                End If
                If fName.IndexOf("_") = -1 Then
                    Return "-1"
                Else
                    Dim sIndex As String = fName.Substring(fName.LastIndexOf("_") + 1, fName.IndexOf(":") - fName.LastIndexOf("_") - 1)
                    If sIndex.Length = 1 Then sIndex = "0" & sIndex
                    Return sIndex
                End If
            End Get
        End Property
        Public fEnabled As Boolean = False
        Public bFail As Boolean = True
        Public bRate As Boolean = False
        Public bEUE As Boolean = False
        Public iRATE As Double = 80.0
        Public ReadOnly Property currentRate As String
            Get
                'Return Statistics.Clients(fName.Substring 
                '"filters_" & C.ClientName & "_" & S.id & ":" & S.type
                Try
                    Dim cName As String = ""
                    If InStr(fName, "_") = 0 Then
                        cName = fName
                    Else
                        cName = fName.Substring(8, fName.IndexOf("_", 8) - 8)
                    End If
                    If fName.IndexOf("_") = -1 Then
                        Return Statistics.CurrentStatistics.Clients(cName).SuccesRate
                    Else
                        Dim sIndex As String = fName.Substring(fName.LastIndexOf("_") + 1, fName.IndexOf(":") - fName.LastIndexOf("_") - 1)
                        If sIndex.Length = 1 Then sIndex = "0" & sIndex
                        Return Statistics.CurrentStatistics.Clients(cName).Slots(sIndex).SuccesRate
                    End If
                Catch ex As Exception
                    Return "-1"
                End Try
            End Get
        End Property
        Public bError As Boolean = False
    End Class
    Private m_nFilters As New List(Of clsNFilter)
    Public ReadOnly Property nFilters As List(Of clsNFilter)
        Get
            Return m_nFilters
        End Get
        'Set(value As List(Of clsNFilter))
        '    m_nFilters = value
        'End Set
    End Property
    Public Function UpdateFilterSettings() As Boolean
        Try
            For Each ucF As clsNFilter In m_nFilters
                Dim fPrefix As String = ucF.fName
                mySettings.ChangeSetting(fPrefix & "_enabled", ucF.ucFilter.chkRuleName.Checked.ToString)
                mySettings.ChangeSetting(fPrefix & "_eue", ucF.ucFilter.rbEUE_Always.Checked.ToString)
                mySettings.ChangeSetting(fPrefix & "_rate", ucF.ucFilter.rbEUE_ratio.Checked.ToString)
                mySettings.ChangeSetting(fPrefix & "_currentrate", ucF.ucFilter.txtRatio_Actual.Text)
                mySettings.ChangeSetting(fPrefix & "_irate", CInt(ucF.ucFilter.nudRatio_Warning.Value).ToString)
            Next
            Return True
        Catch ex As Exception
            WriteError(ex.Message, Err)
            Return False
        End Try
    End Function
    Public Function InitializeFilters() As Boolean
        If m_nFilters.Count > 0 Then
            Return True
            WriteLog("Aborting filter initialization due to already being initialized", eSeverity.Important)
        End If
        Dim bErr As Boolean = False
        Try
            Dim cS As clsStatistics = Statistics.CurrentStatistics
            'enum logparser.clients, add client filter and slot filters
            For Each C As clsClients.clsClient In logParser.Clients
                Dim nFilter As New clsNFilter
                nFilter.fName = C.ClientName
                Dim fPrefix As String = FormatSQLString("filters_" & C.ClientName)
                If HasSetting(fPrefix) Then
                    nFilter.fEnabled = CBool(Setting(fPrefix & "_enabled"))
                    nFilter.bEUE = CBool(Settings(fPrefix & "_eue"))
                    nFilter.bFail = CBool(Settings(fPrefix & "_fail"))
                    nFilter.bRate = CBool(Setting(fPrefix & "_rate"))
                    nFilter.iRATE = CDbl(Setting(fPrefix & "_irate"))
                    nFilter.ucFilter = New ucNotifyFilter
                Else
                    AddSetting(fPrefix, Boolean.TrueString) 'boolean value indicate filter availability
                    AddSetting(fPrefix & "_enabled", Boolean.TrueString)
                    AddSetting(fPrefix & "_eue", Boolean.FalseString)
                    AddSetting(fPrefix & "_rate", Boolean.FalseString)
                    AddSetting(fPrefix & "_fail", Boolean.TrueString)
                    AddSetting(fPrefix & "_irate", "80.0")
                    nFilter.ucFilter = New ucNotifyFilter
                End If
                m_nFilters.Add(nFilter)
                For Each S As clsClientConfig.clsConfiguration.sSlot In C.ClientConfig.Configuration.slots
                    Dim sFilter As New clsNFilter
                    fPrefix = FormatSQLString("filters_" & C.ClientName & "_" & S.id & ":" & S.type)
                    sFilter.fName = fPrefix
                    If HasSetting(fPrefix) Then
                        sFilter.fEnabled = CBool(Setting(fPrefix & "_enabled"))
                        sFilter.bFail = CBool(Settings(fPrefix & "_fail"))
                        sFilter.bEUE = CBool(Settings(fPrefix & "_eue"))
                        sFilter.bRate = CBool(Setting(fPrefix & "_rate"))
                        sFilter.iRATE = CInt(Setting(fPrefix & "_irate"))
                        sFilter.ucFilter = New ucNotifyFilter
                    Else
                        AddSetting(fPrefix, Boolean.FalseString) 'boolean value indicate filter availability
                        AddSetting(fPrefix & "_enabled", Boolean.FalseString)
                        AddSetting(fPrefix & "_fail", Boolean.TrueString)
                        AddSetting(fPrefix & "_eue", Boolean.FalseString)
                        AddSetting(fPrefix & "_rate", Boolean.FalseString)
                        AddSetting(fPrefix & "_irate", "80")
                        sFilter.ucFilter = New ucNotifyFilter
                    End If
                    m_nFilters.Add(sFilter)
                Next
            Next
        Catch ex As Exception
            bErr = True
            WriteError(ex.Message, Err)
        End Try
        Return Not bErr AndAlso CBool(m_nFilters.Count > 0)
    End Function
#End Region
#End Region

#End Region

#Region "Remote clients"
    Public Class clsRemoteClients
        Public Sub Clear()
            Try
                Do While logParser.Clients.Count > 1
                    logParser.RemoveClient(logParser.Clients(1).ClientName)
                Loop
                sqdata.SaveRemoteClients()
            Catch ex As Exception
                WriteError(ex.Message, Err)
            End Try
        End Sub
        Public Sub RemoveRemoteClient(ByVal Name As String)
            Try
                logParser.RemoveClient(Name)
                sqdata.SaveRemoteClients()
            Catch ex As Exception
                WriteError(ex.Message, Err)
            End Try
        End Sub
        Public Sub AddRemoteClient(ByVal Name As String, ByVal Location As String, FCPort As String, PWD As String, FWPort As String, Enabled As Boolean)
            Try
                logParser.AddClient(Name, Location, FCPort, PWD, FWPort, Enabled)
                sqdata.SaveRemoteClients()
            Catch ex As Exception
                WriteError(ex.Message, Err)
            End Try
        End Sub
        Public Sub SetState(ByVal Name As String, ByVal Enabled As Boolean)
            Try
                logParser.SetClientState(Name, Enabled)
                sqdata.SaveRemoteClients()
            Catch ex As Exception
                WriteError(ex.Message, Err)
            End Try
        End Sub
    End Class
    Public RemoteClients As New clsRemoteClients
#End Region

    Public Sub Init()
        'Call after initializing sqdata!
        Try
            m_Settings.Add("liveview", Boolean.FalseString)
            m_Settings.Add("defaultview", "historical")
            m_Settings.Add("interval", "300")
            m_Settings.Add("defaultsummary", "http://fah-web.stanford.edu/psummary.html")
            m_Settings.Add("startwithwindows", Boolean.FalseString)
            m_Settings.Add("startminimized", Boolean.FalseString)
            m_Settings.Add("minimizetotray", Boolean.FalseString)
            m_Settings.Add("startfc", Boolean.FalseString)
            m_Settings.Add("network_port", "49153")
            m_Settings.Add("localname", "local")
            m_Settings.Add("verbose-level", "trivial")
            m_Settings.Add("autodownloadsummary", Boolean.TrueString)
            'Data miner
            m_Settings.Add("parselogseoc", Boolean.TrueString)
            m_Settings.Add("parseoninterval", Boolean.TrueString)
            m_Settings.Add("parserinterval", New TimeSpan(1, 0, 0).ToString)
            'Notify by 
            m_Settings.Add("notify_by", clsNotifyOptions.eNotifyOption.TrayIcon.ToString)
            'Notify by failure
            m_Settings.Add("notifyfail", Boolean.TrueString)
            'Notify by eue
            m_Settings.Add("notifyeue", Boolean.FalseString)
            m_Settings.Add("notifyeue_always", Boolean.TrueString)
            m_Settings.Add("notifyeue_rate", Boolean.FalseString)
            m_Settings.Add("notifyrate", "80")
            'Notify by rules
            m_Settings.Add("usefilterrules", Boolean.FalseString)
            'Notifications eoc
            m_Settings.Add("eocdisable", Boolean.FalseString)
            m_Settings.Add("eocnotify", Boolean.TrueString)
            m_Settings.Add("eoccustomsignature", "")
            m_Settings.Add("eocicon", Boolean.TrueString)
            m_Settings.Add("eoc_interval", New TimeSpan(0, 15, 0).ToString)
            m_Settings.Add("eoc_net_failure", #1/1/2000#.ToString("s"))
            'history form
            m_Settings.Add("history_tcdetails_splitterdistance", "300")
            m_Settings.Add("history_tcmain_splitterdistance", "400")
            m_Settings.Add("history_viewdetails", Boolean.TrueString)
            With notify
                .NotifyEUE = Notify_EUE
                .EUE_by_Rate = Notify_EUE_ByRate
                .EUE_always = Notify_EUE_Always
                .notifyFAILURE = Notify_Failure
                .NotifyRATE = NotifyRate
                .NotifyOption = NotifyOption
                .NotifyRules = Notify_UseRules
            End With
            m_firstRun = Not sqdata.HasSettings
            GetSettings()
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub

End Class
